package com.atguigu.bigdata.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;

public class Dwd_01_BaseLogApp extends BaseAppV1 {
    private final String START = "start";
    private final String DISPLAYS = "displays";
    private final String PAGE = "page";
    private final String ACTIONS = "actions";
    private final String ERR = "err";
    private final String APPVIDEO = "appVideo";

    public static void main(String[] args) {
        new Dwd_01_BaseLogApp().init(
                10001,
                2,
                "Dwd_01_BaseLogApp",
                Constant.TOPIC_ODS_LOG
        );

    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //1.etl   看格式是否是正常的json格式
        SingleOutputStreamOperator<JSONObject> etlStream = etl(stream);

        //2.纠正新老客户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etlStream);
//        validatedStream.print("aaa");
        //3.分流：手工分流的方式，侧输出流

        HashMap<String, DataStream<JSONObject>> streams = splitStream(validatedStream);

        //4.不同的流的数据写出到不同的topic中
        write2Kafka(streams);
    }

    private void write2Kafka(HashMap<String, DataStream<JSONObject>> streams) {
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(ACTIONS).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTIONS));
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(DISPLAYS).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAYS));
        streams.get(APPVIDEO).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_APPVIDEO));
    }

    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        /*
            6种日志
            侧输出流
            主流：启动
            侧输出流：日志、曝光、活动、错误、视频信息
         */
        //泛型擦除   是为了后续编译时，保留泛型  泛型只在源码中，当编译成class时，泛型就不存在了，所以加上{}，保留泛型存起来，防止泛型擦除
        OutputTag<JSONObject> displaysTag = new OutputTag<JSONObject>("displays") {};
        OutputTag<JSONObject> actionsTag = new OutputTag<JSONObject>("actions") {};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err") {};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> appVideoTag = new OutputTag<JSONObject>("appVideo") {};

        SingleOutputStreamOperator<JSONObject> startStream = validatedStream
                .process(new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject obj, Context ctx, Collector<JSONObject> out) throws Exception {
                        //1.找到启动日志
                        JSONObject start = obj.getJSONObject("start");
                        if (start != null) {
                            out.collect(obj);
                        } else {
                            JSONObject common = obj.getJSONObject("common");
                            JSONObject page = obj.getJSONObject("page");

                            //2.曝光
                            JSONArray displays = obj.getJSONArray("displays");
                            if (displays != null){
                                for (int i = 0; i < displays.size();i ++ ){
                                    JSONObject display = displays.getJSONObject(i);
                                    //把common和ts也添加到display中
                                    display.putAll(common);
                                    display.putAll(page);
                                    display.put("ts",obj.getLong("ts"));
                                    ctx.output(displaysTag,display);
                                }
                                obj.remove("displays");

                            }
                            //3.actions
                            JSONArray actions = obj.getJSONArray("actions");
                            if (actions != null) {
                                for (int i = 0; i < actions.size(); i++) {
                                    JSONObject action = actions.getJSONObject(i);
                                    action.putAll(common);
                                    action.putAll(page);
                                    ctx.output(actionsTag,action);
                                }
                                obj.remove("actions");   //把数据中的actions删除
                            }
                            //5.appVideo 播放日志
                            JSONObject appVideo = obj.getJSONObject("appVideo");
                            if (appVideo != null) {
                                ctx.output(appVideoTag,obj);
                                obj.remove("appVideo");
                            }
                            //4.err
                            JSONObject err = obj.getJSONObject("err");
                            if (err != null){
                                ctx.output(errTag,obj);
                                obj.remove("err");
                            }

                            //6.page
                           if (page != null){
                               page.putAll(common);
                               ctx.output(pageTag,obj);
                           }
                        }

                    }
                });



        HashMap<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START,startStream);
        streams.put(DISPLAYS,startStream.getSideOutput(displaysTag));
        streams.put(ERR,startStream.getSideOutput(errTag));
        streams.put(ACTIONS,startStream.getSideOutput(actionsTag));
        streams.put(APPVIDEO,startStream.getSideOutput(appVideoTag));
        streams.put(PAGE,startStream.getSideOutput(pageTag));


        return streams;

    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> etlStream) {
        /*
            新老客户的标记是如何生成的？
                前端埋点数据生成
         */
        return etlStream
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //把第一次观看的新用户加入状态保存
                        firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDateState", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject value) throws Exception {
                        String firstVisitDate = firstVisitDateState.value();
                        Long ts = value.getLong("ts");
                        //获取今天的时间
                        String today = AtguiguUtil.toDate(ts);

                        JSONObject common = value.getJSONObject("common");
                        String isNew = common.getString("is_new");

                        if ("1".equals(isNew)) {
                            if (firstVisitDate == null) {
                                //如果状态里是null，则来的是新用户的首日访问
                                //把今天的日期存入到状态
                                firstVisitDateState.update(today);
                            } else if (!today.equals(firstVisitDate)) {
                                //状态不为空，则需要判断今天和首日访问日期是否一样
                                //如果不一样，证明今天不是首日访问，把1改成0
                                common.put("is_new", "0");
                            }
                            }else {
                            //来的是老用户，如果状态为null，把状态设置为昨天
                            if (firstVisitDate == null) {
                                String yesterday = AtguiguUtil.toDate(ts - 24 * 60 * 60 * 1000);
                                firstVisitDateState.update(yesterday);
                            }

                        }
                        return value;
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(new FilterFunction<String>() {
                    @Override
                    public boolean filter(String s) throws Exception {
                        try {
                            JSON.parseObject(s);
                        }catch (Exception e){
                            System.out.println("日志格式有误，请检测：" + s);
                            return false;
                        }
                        return true;
                    }
                })
                .map(JSON::parseObject);
    }
}
